package com.hu.common.util.adm;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;


/**
 * @author 00355760
 */
public class AspectHelper {

    public static <T extends Annotation> T findAnnotation(ProceedingJoinPoint joinPoint, Class<T> annotation) {
        return AnnotationUtils.findAnnotation(getMethod(joinPoint), annotation);
    }

    public static Method getMethod(ProceedingJoinPoint joinPoint) {
        return getMethodSignature(joinPoint).getMethod();
    }

    public static Object[] getArguments(ProceedingJoinPoint joinPoint) {
        return joinPoint.getArgs();
    }

    public static LinkedHashMap<String, Object> getArgumentsMap(ProceedingJoinPoint joinPoint) {
        final Object[] arguments = getArguments(joinPoint);
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        final String[] parameterNames = methodSignature.getParameterNames();
        final int parameterCount = parameterNames.length;
        LinkedHashMap<String, Object> paramMap = new LinkedHashMap<>(parameterCount);

        int i = 0;
        for (; i < parameterCount; i++) {
            paramMap.put(parameterNames[i], arguments[i]);
        }

        return paramMap;
    }

    public static MethodSignature getMethodSignature(ProceedingJoinPoint joinPoint) {
        return (MethodSignature) joinPoint.getSignature();
    }

}
